const Role = require('../model/role.model')

class RoleService {
    /**
     * 新增角色
     */
    async createRole (roleData) {
        // 插入数据
        try {
            const res = await Role.create(roleData)
            return res
        } catch (error) {
            return {
                errorFlag: 'error',
                errorCode: error.parent.code,
                message: error.parent.sqlMessage,
            }
        }
    }
    /**
     * 按照某一字段查找角色表
     */
    async getRoleInfo ({ role_name, id, role_code }) {
        const whereOpt = {}
        // 短路运算 值存在就拷贝进whereOpt
        role_name && Object.assign(whereOpt, { role_name })
        id && Object.assign(whereOpt, { id })
        role_code && Object.assign(whereOpt, { role_code })
        const res = await Role.findAll({ where: whereOpt })
        return res
    }

    /**
     * 修改角色信息
     */
    async modifyByRoleCode (modifyData, role_code) {
        try {
            const res = await Role.update(modifyData, { where: { role_code } })
            return res
        } catch (error) {
            return {
                errorFlag: 'error',
                message: error,
            }
        }
    }

    /**
     * 按照role_code删除一个角色
     */
    async deleteByRoleCode (role_code) {
        try {
            const res = await Role.destroy({ where: { role_code } })
            return res
        } catch (error) {
            return {
                errorFlag: 'error',
                message: error,
            }
        }
    }

    /**
     * 获取角色列表
     */
    async getRoleList (whereOpt, limit, offect) {
        try {
            const { count, rows } = await Role.findAndCountAll({ where: whereOpt, offset: offect * 1, limit: limit * 1 })
            return { count, rows }
        } catch (error) {
            return {
                errorFlag: 'error',
                message: error,
            }
        }
    }
}

module.exports = new RoleService()